<template>
  <div>
    <!-- 搜索区域 -->
    <i-search ref="iSearch" :model="formData" @search="fetch" @reset="reset">
      <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status">
          <el-option label="未启用" value="1"></el-option>
          <el-option label="已启用" value="2"></el-option>
          <!-- <el-option label="禁用" value="禁用"></el-option> -->
        </el-select>
      </el-form-item>
    </i-search>

    <!-- 表格区域 -->
    <i-table
      :toolbar="toolbar"
      :tableData="tableData"
      :pageInfo="pageInfo"
      :selectionShow="true"
      @handleCurrentChange="handleCurrentChange"
      @handleSizeChange="handleSizeChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        v-for="(item,index) in columnList"
        :key="index"
        :label="item.label"
        :prop="item.prop"
        align="center"
      >
      <template slot-scope="scope">
        <el-button v-if="item.prop==='watch'" type='text' @click='watchImg(scope.row)'>预览</el-button>
        <span v-else>{{filterDist(scope.row[item.prop],item)}}</span>
      </template>
      
      </el-table-column>
     
    </i-table>

    <!-- 新增对话框区域 -->
    <i-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      :width="widthSetting"
      @dialog-before-close="dialogBeforeClose"
      @dialog-cancel="dialogCancel"
      @dialog-confirm="dialogConfirm"
    >
      <el-form :model="dialogFormData" ref="formRef" :rules="formRules" label-width="100px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="排序" prop="sortNumber">
              <el-input v-model="dialogFormData.sortNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item label="商品编号" prop="goodId">
              <el-input v-model="dialogFormData.goodId" ></el-input>
              <el-button type="primary" @click="goodSelected" class="SelectBtn">选择</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="transform: translateY(-33px);margin-top:30px;">
          <el-col :span="12">
            <el-form-item label="有效期起" prop="startTime">
              <el-date-picker
                v-model="dialogFormData.startTime"
                :picker-options="startTimePickerOptions"
                type="date"
                placeholder="选择日期"
                style="width:218px;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效期止" prop="endTime" style="transform: translateX(-30px)">
              <el-date-picker
                v-model="dialogFormData.endTime"
                :picker-options="endTimePickerOptions"
                type="date"
                placeholder="选择日期"
                style="width:218px;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="上传图片" prop="picturePath">
          <div class="btn-box">
            点击上传
            <input type="file" id="addfile" @change="inputChange($event)" />
          </div>
          <div class="imginfourl">{{this.dialogFormData.picturePath}}</div>
        </el-form-item>
      </el-form>
    </i-dialog>

    <!-- 轮播商品选择对话框 -->
    <el-dialog title="商品选择" :visible.sync="selectDialogVisible" width="70%">
      <i-search ref="iSearch" :model="seleteformData" @search="seletefetch" @reset="seletereset">
        <el-form-item label="商品名称" prop="goodName">
          <el-input v-model="seleteformData.goodName"></el-input>
        </el-form-item>
        <el-form-item label="商品编号" prop="goodId">
          <el-input v-model="seleteformData.goodId"></el-input>
        </el-form-item>
      </i-search>
      <i-table
        :tableData="seletetableData"
        :pageInfo="selectpageInfo"
        :selectionShow="true"
        @handleCurrentChange="selecthandleCurrentChange"
        @handleSizeChange="selecthandleSizeChange"
        @selection-change="SelectionChange"
      >
        <el-table-column
          v-for="(item,index) in SelectcolumnList"
          :key="index"
          :label="item.label"
          :prop="item.prop"
          align="center"
        ></el-table-column>
      </i-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="selectDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="seleteSubmit">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 注意首两个字母要大写，这样才会被识别出来所调用的子组件
import ISearch from "../../components/common/i-search.vue";
import ITable from "../../components/common/i-table.vue";
import IDialog from "../../components/common/i-dialog.vue";
import req from "@/api/home-pic-manager.js";
import axios from "axios";
export default {
  name: "home-pic-manage",
  data() {
    return {
      // 搜索框数据
      formData: {},
      // 选择框数据
      selectformData: {},
      // 新增对话框数据
      dialogFormData: {
        sortNumber:'',
        goodId:'',
        startTime:'',
        endTime:'',
        picturePath:''
      },
      // 商品查询表格
      seletetableData: [],
      // 商品搜索框
      seleteformData: {
        goodName:'',
        goodId:''
      },
      // 设置新增对话框默认隐藏
      dialogVisible: false,

      // 设置轮播商品选择对话框默认隐藏
      selectDialogVisible: false,
      // 新增对话框标题
      dialogTitle: "新增轮播图",
      // 会话框宽度设置
      widthSetting: 800,
      // 存储选中首页轮播信息的id
      multipId: [],
      // 存储选中商品信息的版本号
      GoodsId: [],
      multipVersion: [],

      // 分页数据
      pageInfo: {
        pageIndex: 1,
        pageSize: 5,
        total: 0
      },
      // 商品选择分页
      selectpageInfo: {
        pageIndex: 1,
        pageSize: 5,
        total: 0
      },
      startTimePickerOptions: {
        disabledDate: value => {
          return this.dialogFormData.endTime < value;
        }
      },
      endTimePickerOptions: {
        disabledDate: value => {
          return this.dialogFormData.startTime > value;
        }
      },
      // 多个按钮数据设置
      toolbar: [
        {
          btnName: "新增",
          type: "primary",
          // 设置按钮的触发事件
          func: () => {
            // console.log(this.dialogVisible);
            this.dialogVisible = true;
          }
        },

        {
          btnName: "删除",
          type: "primary",
          func: async () => {
            if (this.multipId.length !== 0) {
              const confirmResult = await this.$confirm(
                "此操作将永久删除所选轮播图, 是否继续?",
                "提示",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
                }
              ).catch(err => err);
              if (confirmResult !== "confirm") {
                this.$message("已取消删除");
                this.fetch();
              } else {
                console.log(this.multipId.join(","));
                req("deteleRotationChart", {
                  rotationChartId: this.multipId.join(",")
                }).then(data => {
                  console.log(data);
                  if (data.code !== 0) {
                    this.$message.error(data.msg);
                    this.fetch();
                  }
                  this.$message.success(data.msg);
                  this.fetch();
                });
              }
            }
          }
        },
        {
          btnName: "启用",
          type: "primary",
          func: async () => {
            if (this.multipVersion.length !== 0) {
              const confirmResult = await this.$confirm(
                "此操作将启用所选轮播图, 是否继续?",
                "提示",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
                }
              ).catch(err => err);
              if (confirmResult !== "confirm") {
                this.$message("已取消启用");
                this.fetch();
              } else {
                req("updateRotationChartStatus", {
                  rotationChartId: this.multipId.join(","),
                  status: "2",
                  versionString: this.multipVersion.join(",")
                }).then(data => {
                  // console.log(data)
                  if (data.code !== 0) {
                     this.$message.error(data.msg);
                     this.fetch();
                  }
                  this.$message.success(data.msg);
                  this.fetch();
                });
              }
            }
          }
        },
        {
          btnName: "禁用",
          type: "primary",
          func: async () => {
            if (this.multipVersion.length !== 0) {
              const confirmResult = await this.$confirm(
                "此操作将禁用所选轮播图, 是否继续?",
                "提示",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
                }
              ).catch(err => err);
              if (confirmResult !== "confirm") {
                 this.$message("已取消禁用");
                 this.fetch();
              } else {
                req("updateRotationChartStatus", {
                  rotationChartId: this.multipId.join(","),
                  status: "1",
                  versionString: this.multipVersion.join(",")
                }).then(data => {
                  // console.log(data)
                  if (data.code !== 0) {
                    this.$message.error(data.msg);
                    this.fetch();
                  }
                  this.$message.success(data.msg);
                  this.fetch();
                });
              }
            }
          }
        }
      ],
      // 表格表头数据
      columnList: [
        { label: "排序", prop: "sortNumber" },
        { label: "图片路径", prop: "picturePath"},
        { label: "状态", prop: "status" },
        { label: "预览",prop:'watch',distName:'picturePath' },
        { label: "有效期起", prop: "startTime" },
        { label: "有效期止", prop: "endTime" }
      ],
      // 商品选择
      SelectcolumnList: [
        { label: "商品编号", prop: "goodId" },
        { label: "商品名称", prop: "goodName" },
        { label: "一级分类名称", prop: "firstClass" },
        { label: "二级分类名称", prop: "secondClass" }
      ],
      // 表格内容数据
      tableData: [],
      formRules: {
        sortNumber: [
          { required: true, message: "请输入排序", trigger: "change" }
        ],
        startTime: [
          { required: true, message: "请选择有效期起始时间", trigger: "change" }
        ],
        endTime: [
          { required: true, message: "请选择有效期停止时间", trigger: "change" }
        ],
        goodId: [{ required: true, message: "请输入商品", trigger: "change" }]
      }
    };
  },
  watch(){},
  // 挂载完毕之前加载数据
  mounted() {
    this.fetch();
  },
  methods: {
    watchImg(data){
      console.log('img',data)
      window.open(data.picturePath)
    },
    filterDist(value,item){
      if(item.distName){
        return this[item.distName].filter(distItem => {
          return distItem.value === value
        })[0].label
      }else{
        return value
      }
    },
    inputChange(event) {
      let form = new FormData();
      let file = document.getElementById("addfile").files[0];

      form.append("multipartFile", file, file.name);
      axios({
        method: "post",
        url: "http://120.76.142.108:8080/pc/image/upload",
        data: form,
        headers: {
          "Content-Type": "Multipart/form-data"
        }
      }).then(data => {
        console.log("data", data);
        if(data.data.code === 0){
this.dialogFormData.picturePath = data.data.data;
         this.$notify({
          title: '成功',
          message:data.data.msg,
          type: 'success'
        });
        }else{
          this.$notify({
          title: '失败',
          message:data.data.msg,
          type: 'warning'
        });
        }
        
      });
    },
    fetch() {
      this.pageInfo.pageIndex = 1;
      this.pageInfo.pageSize = 5;
      this.search();
    },
    seletefetch() {
      this.selectpageInfo.pageIndex = 1;
      this.selectpageInfo.pageSize = 5;
      this.seletesearch();
    },
    search() {
      console.log(typeof this.formData.status);
      req("getTableData", {
        status: this.formData.status,
        pageSize: this.pageInfo.pageSize,
        pageNum: this.pageInfo.pageIndex
      }).then(data => {
        console.log(data);
        this.pageInfo.total = data.data.total;
        this.pageInfo.pageSize = data.data.pageSize;
        this.pageInfo.pageNum = data.data.pageNum;
        this.tableData = data.data.list;
        console.log(this.tableData);
        // 把返回的状态数据替换成对应文字
        this.tableData.forEach(item => {
          if (item.status === 1) {
            item.status = "未启用";
          } else if (item.status === 2) {
            item.status = "已启用";
          }
        });
        // 把返回的开始时间戳转化为标准时间
        this.tableData.forEach(item => {
          let timeobj = new Date(item.startTime);
          let month = timeobj.getMonth() + 1;
          let year = timeobj.getFullYear();
          let day = timeobj.getDate();
          let time = year + " - " + month + " - " + day;
          item.startTime = time;
        });
        // 把返回的截至时间戳转化为标准时间
        this.tableData.forEach(item => {
          let timeobj = new Date(item.endTime);
          let month = timeobj.getMonth() + 1;
          let year = timeobj.getFullYear();
          let day = timeobj.getDate();
          let time = year + " - " + month + " - " + day;
          item.endTime = time;
        });
      });
    },
    reset() {
      this.fetch();
    },
    seletereset() {
      this.seletefetch();
    },
    // 在售商品选择
    seletesearch() {
      req("listSaleGood", {
        ...this.seleteformData,
        pageSize: this.selectpageInfo.pageSize,
        pageNum: this.selectpageInfo.pageIndex
      }).then(data => {
        console.log("select", data);
        this.selectpageInfo.total = data.data.total;
        this.selectpageInfo.pageSize = data.data.pageSize;
        this.selectpageInfo.pageIndex = data.data.pageNum;
        this.seletetableData = data.data.list;
      });
    },

    // 每页数据条数
    handleSizeChange(value) {
      this.pageInfo.pageSize = value;
      this.search();
    },
    // 当前页码数
    handleCurrentChange(value) {
      this.pageInfo.pageIndex = value;
      this.search();
    },
    handleSelectionChange(rows) {
      // console.log("rows", rows);
      this.multipId = [];
      this.multipVersion = [];
      rows.forEach(item => {
        this.multipId.push(item.rotationChartId);
        this.multipVersion.push(item.version);
      });
    },
    selecthandleSizeChange(value) {
      this.selectpageInfo.pageSize = value;
      this.seletesearch();
    },
    selecthandleCurrentChange(value) {
      this.selectpageInfo.pageIndex = value;
      this.seletesearch();
    },
    SelectionChange(rows) {
      // console.log(rows)
      this.GoodsId = [];
      rows.forEach(item => {
        this.GoodsId.push(item.goodId);
      });
    },
    dialogCancel() {
      console.log('新增会话框要关闭啦')
      this.fetch();
      this.dialogVisible = false;
      this.$refs.formRef.resetFields();
    },
    dialogBeforeClose() {
      console.log('新增会话框要隐藏啦')
      this.fetch();
      this.$refs.formRef.resetFields();
      this.dialogVisible = false;
    },
    // 新增轮播图
    dialogConfirm() {
      //  let ty= String(this.dialogFormData.endTime)
      //   console.log(typeof ty)
      //   console.log(ty)
      // console.log(typeof this.dialogFormData.endTime*1)
      (this.dialogFormData.sortNumber = parseInt(
        this.dialogFormData.sortNumber
      )),
        (this.dialogFormData.startTime = String(this.dialogFormData.startTime));
      this.dialogFormData.endTime = String(this.dialogFormData.endTime);
      this.$refs.formRef.validate(async valid => {
        if (!valid) return;
        req("addRotationChart", {
          ...this.dialogFormData
        }).then(data => {
          // console.log(data)
          if (data.code !== 0) {
            return this.$message.error(data.msg);
          } else {
            this.$message.success(data.msg);
            this.dialogVisible = false;
            this.fetch();
          }
        });
      });
    },
    // 点击选择弹出轮播选择对话框
    goodSelected() {
      this.selectDialogVisible = true;
      this.seletefetch();
    },
    selectDialogCancel() {
      this.selectDialogVisible = false;
    },
    // 提交商品编号
    seleteSubmit() {
      console.log(this.GoodsId);
      if (this.GoodsId.length !== 1) {
        this.$message.error("请选择单个商品！");
      } else {
        this.dialogFormData.goodId = this.GoodsId[0];
        this.selectDialogVisible = false;
      }
    }
  },
  // 子组件注册
  components: {
    ISearch,
    ITable,
    IDialog
  }
};
</script>

<style lang="scss" scoped>
// 对话框选取文件按钮
.el-upload__tip {
  margin-left: 10px;
}

// 对话框商品输入框
// .el-input__inner {
//   width: 218px;
// }
.el-input{
  width: 218px;
}
// 搜索输入框
.goodsinput {
  width: 150px;
}
//  选择按钮
.SelectBtn {
  position: relative;
  transform: translateX(15px);
}
</style>
